<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="姓名" prop="stuName">
        <el-input v-model="queryParams.stuName" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="请输入昵称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="性别" prop="stuSex">
        <el-select v-model="queryParams.stuSex" placeholder="请选择性别" clearable>
          <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="学号" prop="stuCode">
        <el-input v-model="queryParams.stuCode" placeholder="请输入学号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="登录手机号" prop="tel">
        <el-input v-model="queryParams.tel" placeholder="请输入登录手机号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="校区" prop="schoolName">
        <el-input v-model="queryParams.schoolName" readonly="readonly" @click.native="openSelectSchool(1)"
          placeholder="请输入校区" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="上线" prop="state">
        <el-select v-model="queryParams.state" clearable>
          <el-option v-for="dict in dict.type.common_state" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="分班" prop="clzzFlag">
        <el-select v-model="queryParams.clzzFlag" clearable>
          <el-option v-for="dict in dict.type.common_state" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="学生类型" prop="stuType">
        <el-select v-model="queryParams.stuType" clearable>
          <el-option v-for="dict in dict.type.stu_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="会员类型" prop="memberType">
        <el-select v-model="queryParams.memberType" clearable>
          <el-option v-for="dict in dict.type.stu_member_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['school:student:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['school:student:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['school:student:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['school:student:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="姓名" align="center" prop="stuName" />
      <el-table-column label="会员类型" align="center" prop="memberType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.stu_member_type" :value="scope.row.memberType" />
        </template>
      </el-table-column>

      <el-table-column label="性别" align="center" prop="stuSex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.stuSex" />
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="登录手机号" align="center" prop="tel" />
      <el-table-column label="校区" align="center" prop="schoolName" />
      <el-table-column label="班级" align="center" prop="clzzNames">
        <template slot-scope="scope">
          <el-tag size="mini">
            {{scope.row.clzzNames}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="带班老师" align="center" prop="teacherNames">
        <template slot-scope="scope">
          <el-tag size="mini">
            {{scope.row.teacherNames}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上线" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.common_state" :value="scope.row.state" />
        </template>
      </el-table-column>
      <el-table-column label="会员到期日" align="center" prop="validTo">

      </el-table-column>
      <el-table-column label="学习时间" align="center" prop="studyInfo">

      </el-table-column>
      <el-table-column label="学习进度" align="center" prop="bookInfo">

      </el-table-column>
      <el-table-column label="添加时间" align="center" prop="gmtCreate" />
      <el-table-column label="操作" fixed="right" width="200" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-user" @click="handleUpdate(scope.row,'renew')"
            v-hasPermi="['school:student:renew']">续费</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row,'update')"
            v-hasPermi="['school:student:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['school:student:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改学生信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" v-if="formType=='renew'">
        <el-form-item label="续费期限" prop="memberType">
          <el-radio-group v-model="form.memberType" @input="switchMemberType">
            <el-radio-button v-for="dict in dict.type.stu_member_type" :key="dict.value" :label="dict.value"
              border>{{dict.label}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker v-model="form.startDate" @change="selectValidTo" value-format="yyyy-MM-dd HH:mm:ss"
            date-format="yyyy-MM-dd" type="date" placeholder="选择开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到期日期">
          <el-date-picker v-model="form.newValidTo" value-format="yyyy-MM-dd HH:mm:ss"
            date-format="yyyy-MM-dd" type="date" readonly placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px" v-if="formType=='update'">
        <el-row>
          <el-col :span="12">
            <el-form-item label="头像" prop="avatar">
              <el-upload :action="uploadUrl" :before-upload="beforeImageUpload" list-type="picture-card"
                :show-file-list="false" :on-success="uploadImageSuccess" :data="{'relationType':'STU_AVATAR'}"
                :auto-upload="true" :headers="headers" accept="image/*">
                <img v-if="avatar" :src="avatar" class="uploadImage">
                <i v-else class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="stuName">
              <el-input v-model="form.stuName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="stuSex">
              <el-select v-model="form.stuSex" placeholder="请选择性别">
                <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="form.age" :min="1" placeholder="请输入年龄" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学号" prop="stuCode">
              <el-input v-model="form.stuCode" placeholder="创建时后台自动生成" readonly="readonly" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录手机号" prop="tel">
              <el-input v-model="form.tel" placeholder="请输入登录手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录密码" prop="pwd">
              <el-input v-model="form.pwd" placeholder="输入密码,表示新密码内容,若新建时候,密码为空则为默认密码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生日" prop="birthDay">
              <el-date-picker clearable v-model="form.birthDay" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择生日">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="校区" prop="schoolName">
              <el-input v-model="form.schoolName" @click.native="openSelectSchool(2)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省、市、区" prop="provinceAndCityAndDistrict">
              <el-cascader placeholder="请选择省、市、区" v-model="form.provinceAndCityAndDistrict" :options="options"
                @lazy-load="selectLoadOptions"
                :props="{ lazy: true, lazyLoad: selectLoadOptions,value:'regionId',label:'regionName' }"
                clearable></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上线" prop="state">
              <el-select v-model="form.state" placeholder="请选择是否上线">
                <el-option v-for="dict in dict.type.common_state" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.id == null">
            <el-form-item label="会员有效期" prop="memberType">
              <el-radio-group v-model="form.memberType">
                <el-radio-button v-for="dict in dict.type.stu_member_type.filter(item => item.value != 3)"
                  :key="dict.value" :label="dict.value" border>{{dict.label}}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级" prop="clzzNames" v-if="form.id != null">
              <el-tag>{{form.clzzNames}}</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="老师" prop="teacherNames" v-if="form.id != null">
              <el-tag>{{form.teacherNames}}</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学员类型" prop="stuType">
              <el-radio-group v-model="form.stuType">
                <el-radio-button v-for="dict in dict.type.stu_type" :key="dict.value" :label="dict.value"
                  border>{{dict.label}}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员开始日期" prop="validFrom">
              <el-date-picker clearable v-model="form.validFrom" type="date" value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd" placeholder="请选择会员开始日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitLoading">
          {{ submitLoading ? '提交中...' : '确定' }}</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择校区 -->
    <SelectSchool ref="selectSchool" :open="selectFlag" @selected-data="selectSchoolData"
      @close-select-window="closeSelectSchool" />
  </div>
</template>

<script>
  import {
    listStudent,
    getStudent,
    delStudent,
    addStudent,
    updateStudent,
    updateStudentRenew
  } from "@/api/bus_web/school/student";
  import {
    loadOptions
  } from "@/api/system/sys_region";
  import {
    isEmpty
  } from "@/utils/validate"
  import {
    mapState
  } from 'vuex';
  import store from "@/store";
  import SelectSchool from "../schoolinfo/select.vue"
  import {
    getToken
  } from '@/utils/auth'
  export default {
    name: "Student",
    dicts: ['sys_user_sex', 'common_state', 'stu_member_type', 'stu_type'],
    components: {
      SelectSchool
    },
    data() {
      return {
        headers: {
          'Authorization': getToken()
        },
        selectRow: null,
        uploadUrl: process.env.VUE_APP_BASE_API + '/fileresource/file/fileUpload',
        // 遮罩层
        loading: true,
        // 是否显示校区选择
        selectFlag: false,
        submitLoading: false,
        options: [],
        // form类型
        formType: 'update',
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 学生信息表格数据
        studentList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        //头像信息
        avatar: null,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          stuName: null,
          avatar: null,
          stuSex: null,
          stuCode: null,
          tel: null,
          birthDay: null,
          schoolId: null,
          schoolName: null,
          schoolIdArray: [],
          province: null,
          city: null,
          nickName: null,
          district: null,
          address: null,
          state: null,
          gmtCreate: null,
          gmtModify: null,
          memberType: null,
          queryProvinceAndCityAndDistrict: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          schoolName: [{
            required: true,
            message: "校区不能为空",
            trigger: "blur"
          }],
          state: [{
            required: true,
            message: "上线不能为空",
            trigger: "change"
          }],
          stuName: [{
            required: true,
            message: "姓名不能为空",
            trigger: "blur"
          }],
          tel: [{
            required: true,
            message: "登录手机号不能为空",
            trigger: "blur"
          }],
          validFrom: [{
            required: true,
            message: "有效开始日期不能为空",
            trigger: "blur"
          }],
          memberType: [{
            required: true,
            message: "请选择会员有效期",
            trigger: "blur"
          }],
          stuType: [{
            required: true,
            message: "请选择学员类型",
            trigger: "blur"
          }]
        }
      };
    },
    computed: {
      ...mapState({
        school: state => state.selectSchool.school,
        schoolSelectModel: state => state.selectSchool.schoolSelectModel,
      })
    },
    created() {
      this.getList();
    },
    methods: {
      //图片上传
      beforeImageUpload(file) {
        this.$modal.loading('正在上传文件...')
        return true
      },
      //图片上传成功
      uploadImageSuccess(res, file, fileList) {
        this.avatar = res.data.url
        this.form.avatar = res.data.id
        this.$modal.closeLoading()
      },

      /**省 市 区*/
      selectLoadOptions(node, resolve) {
        var query = {
          regionLevel: node.level + 1,
          parentId: node.value || null
        }
        loadOptions(query).then(response => {
          resolve(response.data);
        });
      },
      /** 查询学生信息列表 */
      getList() {
        this.loading = true;
        listStudent(this.queryParams).then(response => {
          this.studentList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          stuName: null,
          avatar: null,
          stuSex: null,
          stuCode: null,
          tel: null,
          birthDay: null,
          schoolId: null,
          schoolName: null,
          province: null,
          city: null,
          district: null,
          address: null,
          state: null,
          gmtCreate: null,
          gmtModify: null,
          deleted: null,
          createBy: null,
          updateBy: null,
          classInfo: null,
          teacherName: null,
          memberType: null,
          teacherNames: [],
          teacherNames: [],
          validFrom: null,
          validTo: null,
          newValidTo: null,
          startDate: null,
          stuType: null
        };
        this.resetForm("form");
        this.submitLoading = false
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.queryParams.schoolIdArray = []
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加学生信息";
        this.formType = 'update'
      },
      /** 修改按钮操作 */
      handleUpdate(row, op) {
        this.reset()
        this.formType = op
        this.selectRow = row
        const id = row.id || this.ids
        getStudent(id).then(response => {
          this.form = response.data;
          this.avatar = response.data.avatarURL
          delete this.form.avatarURL
          this.open = true;
          if (op == 'renew') {
            this.form.memberType = null
            this.form.startDate = this.form.validTo
            this.title = "学员续费";
          } else {
            this.title = "修改学生信息";
          }
        });
      },
      /* 切换日期*/
      switchMemberType(value) {
        let days = 0
        if (1 == value) {
          days = 92
        } else if (2 == value) {
          days = 183
        } else if (3 == value) {
          days = 275
        } else if (4 == value) {
          days = 366
        }
        if (!isEmpty(this.form.startDate)) {
          const newDate = new Date(this.form.startDate)
          newDate.setDate(new Date(this.form.startDate).getDate() + days)
          this.$set(this.form, 'newValidTo', this.parseTime(newDate));
        }

      },
      selectValidTo(time) {
        if (!isEmpty(this.form.memberType)) {
          let value = this.form.memberType
          let days = 0
          if (1 == value) {
            days = 92
          } else if (2 == value) {
            days = 183
          } else if (3 == value) {
            days = 275
          } else if (4 == value) {
            days = 366
          }
          const newDate = new Date(time)
          newDate.setDate(new Date(time).getDate() + days)
          this.$set(this.form, 'newValidTo', this.parseTime(newDate));
        }
      },
      /** 提交按钮 */
      submitForm() {
        this.submitLoading = true
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              if (this.formType == 'renew') {
                var jsonData = {
                  'id': this.form.id,
                  'memberType': this.form.memberType,
                  'startDate': this.form.startDate
                }
                updateStudentRenew(jsonData).then(response => {
                  this.$modal.msgSuccess("续费成功");
                  this.open = false;
                  this.getList();
                }).finally(() => {
                  this.submitLoading = false
                })
                return
              }
              updateStudent(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.submitLoading = false
              })
            } else {
              addStudent(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.submitLoading = false
              })
            }
          } else {
            this.submitLoading = false
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除学生信息编号为"' + ids + '"的数据项？').then(function() {
          return delStudent(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('school/student/export', {
          ...this.queryParams
        }, `学生列表_${new Date().getTime()}.xlsx`)
      },
      //选择校区
      openSelectSchool(selectVal) {
        this.selectFlag = true
        // selectVal =1 查询模式 =2 创建、修改模式
        this.$store.dispatch('selectSchool/cleanSchool')
        this.$store.dispatch('selectSchool/setSchoolSelectModel', selectVal)
      },
      closeSelectSchool() {
        this.selectFlag = false
      },
      //确定校区
      selectSchoolData() {
        this.closeSelectSchool()
        if (this.schoolSelectModel == 2) {
          this.form.schoolName = this.school[0].schoolName
          this.form.schoolId = this.school[0].id
          this.$refs.form.clearValidate(['schoolName']);
        } else {
          this.queryParams.schoolName = this.school.map(item => item.schoolName).join(',')
          this.queryParams.schoolIdArray = this.school.map(item => item.id)
        }
        this.$store.dispatch('selectSchool/cleanSchool')
      }
    }
  };
</script>
<style scoped>
  .uploadImage {
    width: 100%;
    height: 100%;
  }
</style>
